package com.example;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttCallback;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ChatClientGUI extends JFrame {
    private ChatClient chatClient;
    private JTextField usernameField;
    private JTextField messageField;
    private JTextArea chatArea;

    public ChatClientGUI(String title) {
        super(title);
        initializeUI();
    }

    private void initializeUI() {
        // 设置窗口大小和布局
        setSize(400, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // 用户名输入框
        JPanel usernamePanel = new JPanel();
        usernamePanel.add(new JLabel("用户名:"));
        usernameField = new JTextField(20);
        usernamePanel.add(usernameField);
        // 连接按钮
        JButton connectButton = new JButton("连接");
        connectButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                initializeClient(); // 调用初始化方法
            }
        });
        usernamePanel.add(connectButton);
        add(usernamePanel, BorderLayout.NORTH);

        // 消息显示区域
        chatArea = new JTextArea();
        chatArea.setEditable(false);
        chatArea.setLineWrap(true);
        JScrollPane scrollPane = new JScrollPane(chatArea);
        add(scrollPane, BorderLayout.CENTER);

        // 消息输入框和发送按钮
        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new BorderLayout());
        messageField = new JTextField(20);
        inputPanel.add(messageField, BorderLayout.CENTER);

        JButton sendButton = new JButton("发送");
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    String message = messageField.getText().trim();
                    if (!message.isEmpty()) {
                        // 发送消息时，包含用户名
                        chatClient.sendMessage(usernameField.getText().trim(), message);
                        messageField.setText(""); // 清空输入框
                        //chatArea.append("自己发送: " + usernameField.getText().trim() + ": " + message + "\n"); // 显示自己发送的消息
                    }
                } catch (MqttException ex) {
                    chatArea.append("发送消息失败: " + ex.getMessage() + "\n");
                }
            }
        });
        inputPanel.add(sendButton, BorderLayout.EAST);
        add(inputPanel, BorderLayout.SOUTH);

        // 显示窗口
        setVisible(true);
    }

    private void initializeClient() {
        try {
            String username = usernameField.getText().trim();
            if (!username.isEmpty()) {
                chatClient = new ChatClient(username); // 创建 ChatClient 实例
                chatClient.subscribe("chat/topic"); // 订阅主题
                chatClient.callback(new MqttCallback() {
                    @Override
                    public void connectionLost(Throwable cause) {
                        chatArea.append("与 MQTT Broker 的连接丢失: " + cause.getMessage() + "\n");
                    }

                    @Override
                    public void messageArrived(String topic, MqttMessage message) throws Exception {
                        // 处理接收到的消息
                        String receivedMessage = new String(message.getPayload());
                        // 确保在 EDT 上更新 UI
                        SwingUtilities.invokeLater(() -> {
                            chatArea.append("收到消息: " + receivedMessage + "\n"); // 显示接收到的消息
                        });
                    }

                    @Override
                    public void deliveryComplete(IMqttDeliveryToken token) {
                        // 消息发送完成的回调
                    }
                });
            } else {
                JOptionPane.showMessageDialog(this, "请输入用户名！");
            }
        } catch (MqttException ex) {
            JOptionPane.showMessageDialog(this, "连接 MQTT Broker 失败: " + ex.getMessage());
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new ChatClientGUI("MQTT IM 客户端"));
    }
}